package com.wangsh.userscenter.users.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wangsh.userscenter.common.service.BaseServiceImpl;
import com.wangsh.userscenter.common.util.ConstatFinalUtil;
import com.wangsh.userscenter.common.util.PageInfoUtil;
import com.wangsh.userscenter.system.pojo.ARegion;
import com.wangsh.userscenter.system.service.ISystemService;
import com.wangsh.userscenter.users.dao.IAAdminsDao;
import com.wangsh.userscenter.users.dao.IARoleDao;
import com.wangsh.userscenter.users.dao.IAUsersDao;
import com.wangsh.userscenter.users.dao.IAUsersExtendDao;
import com.wangsh.userscenter.users.pojo.AAdmins;
import com.wangsh.userscenter.users.pojo.ARole;
import com.wangsh.userscenter.users.pojo.AUsers;
import com.wangsh.userscenter.users.pojo.AUsersExtend;
import com.wangsh.userscenter.users.service.IUsersService;

/**
 * 用户Service的实现类
 * @author WangshSxt
 *
 */
@Service("usersService")
public class UsersServiceImpl extends BaseServiceImpl implements IUsersService
{
	@Resource
	private IAAdminsDao adminsDao;
	@Resource
	private IARoleDao roleDao;
	@Resource
	private IAUsersDao usersDao;
	@Resource
	private IAUsersExtendDao usersExtendDao;
	
	@Resource
	private ISystemService systemService;
	
	@Override
	public JSONObject saveOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject() ; 
		
		/* 按照用户名查询管理员 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", admins.getEmail());
		AAdmins adminsRes = this.findOneAdminsService(condMap);
		if(adminsRes != null)
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
			return resultJSON ; 
		}
		
		int res =  this.adminsDao.save(admins);
		
		/*String str = null ; 
		str.toString() ; */
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* id */
			dataJSON.put("id", admins.getId());
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	@Override
	public AAdmins findOneAdminsService(Map<String, Object> condMap)
	{
		return this.adminsDao.findOne(condMap);
	}

	@Override
	public JSONObject updateOneAdminsService(AAdmins admins)
	{
		JSONObject resultJSON = new JSONObject() ; 
		
		/*
		 * 修改的时候,邮箱不能重复
		 * 先查询一遍,如何做?
		 * ~正常的更新,邮箱不更新,下面的情况成立吗
		 * 
		 * HeadController
		 * if(res > 0 )
		 * {
		 *  成功
		 * }else
		 * {
		 *  失败
		 * }
		 * 
		 * BackController
		 * if(res > 0 )
		 * {
		 *  成功
		 * }else
		 * {
		 *  失败
		 * }
		 * 
		 * */
		/* 按照用户名查询管理员 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", admins.getEmail());
		AAdmins adminsRes = this.findOneAdminsService(condMap);
		if(adminsRes != null && adminsRes.getId() != admins.getId())
		{
			/* 什么情况下,进入到此代码
			 * 输入的邮箱和其它邮箱一致的时候才进入到这里面
			 * ~根据邮箱肯定可以查询出结果
			 * ~查询出的结果(adminsRes)不是自己(参数中的对象)_(admins),只要两个id不一样
			 *  */
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
			return resultJSON ; 
		}
		
		int res =  this.adminsDao.update(admins);
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* id */
			dataJSON.put("id", admins.getId());
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	@Override
	public JSONObject deleteOneAdminsService(Map<String, Object> condMap)
	{
		JSONObject resultJSON = new JSONObject() ; 
		int res =  this.adminsDao.delete(condMap);
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	/**
	 * 实现了分页功能
	 * 实现了查询多条,不分页的功能
	 * 如何让两种情况并存,都支持
	 * 
	 * ~Page这个对象和Mybatis插件绑定紧密
	 * ~将来如果换成其它的dao框架,分页就无法使用
	 * ~所有在jsp页面上写的代码都要改(Page里面的属性和其它框架的分页方法的属性不一样)
	 * 
	 * ~要想分页,有两个必备条件????
	 * ~总条数,每页多少条
	 */
	@Override
	public Map<String,Object> findCondListAdminsService(PageInfoUtil pageInfoUtil,Map<String,Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		/* 处理关键字的模糊匹配 */
		if(condMap.get("keyword") != null)
		{
			condMap.put("keyword", "%" + condMap.get("keyword") +  "%");
		}
		if(pageInfoUtil != null)
		{
			/* 分页查询 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AAdmins> list = this.adminsDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("list", list);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			resultMap.put("pageInfoUtil", pageInfoUtil);
			return resultMap ;
		}
		List<AAdmins> list = this.adminsDao.findList(condMap) ; 
		resultMap.put("list", list);
		return resultMap;
	}

	@Override
	public JSONObject saveOneRoleService(ARole role)
	{
		JSONObject resultJSON = new JSONObject() ; 
		int res =  this.roleDao.save(role);
		
		/*String str = null ; 
		str.toString() ; */
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* id */
			dataJSON.put("id", role.getId());
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	@Override
	public ARole findOneRoleService(Map<String, Object> condMap)
	{
		return this.roleDao.findOne(condMap);
	}

	@Override
	public JSONObject updateOneRoleService(ARole role)
	{
		JSONObject resultJSON = new JSONObject() ; 
		int res =  this.roleDao.update(role);
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* id */
			dataJSON.put("id", role.getId());
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	@Override
	public JSONObject deleteOneRoleService(Map<String, Object> condMap)
	{
		JSONObject resultJSON = new JSONObject() ; 
		int res =  this.roleDao.delete(condMap);
		
		if(res > 0 )
		{
			/* 成功 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			JSONObject dataJSON = new JSONObject() ; 
			/* 影响的条数 */
			dataJSON.put("effect", res);
			
			resultJSON.put("data", dataJSON);
		}else
		{
			/* 失败 */
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON ; 
	}

	/**
	 * 实现了分页功能
	 * 实现了查询多条,不分页的功能
	 * 如何让两种情况并存,都支持
	 * 
	 * ~Page这个对象和Mybatis插件绑定紧密
	 * ~将来如果换成其它的dao框架,分页就无法使用
	 * ~所有在jsp页面上写的代码都要改(Page里面的属性和其它框架的分页方法的属性不一样)
	 * 
	 * ~要想分页,有两个必备条件????
	 * ~总条数,每页多少条
	 */
	@Override
	public Map<String, Object> findCondListRoleService(PageInfoUtil pageInfoUtil,Map<String,Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String,Object>() ; 
		/* 处理关键字的模糊匹配 */
		if(condMap.get("keyword") != null)
		{
			condMap.put("keyword", "%" + condMap.get("keyword") +  "%");
		}
		if(pageInfoUtil != null)
		{
			/* 分页查询 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<ARole> list = this.roleDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("list", list);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			resultMap.put("pageInfoUtil", pageInfoUtil);
			return resultMap ; 
		}
		List<ARole> list = this.roleDao.findList(condMap);
		resultMap.put("list", list);
		return resultMap ; 
	}
	
	@Override
	public JSONObject saveOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();
		// 查询用户的单点登陆id是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", users.getEmail() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null)
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
			return resultJSON;
		}
		int res = this.usersDao.save(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 保存用户扩展信息 */
			AUsersExtend usersExtend = users.getUsersExtend()  ;
			if(usersExtend == null)
			{
				usersExtend = new AUsersExtend();
			}
			
			usersExtend.setUsersId(users.getId());
			usersExtend.setCreateTime(new Date());
			usersExtend.setUpdateTime(new Date());
			this.saveOneUsersExtendService(usersExtend);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersService(AUsers users)
	{
		JSONObject resultJSON = new JSONObject();

		/*查询用户的单点登陆id是否存在*/
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("email", users.getEmail() + "");
		AUsers usersRes = this.findOneUsersService(condMap);
		if (usersRes != null && usersRes.getId() != users.getId())
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
			return resultJSON;
		}

		int res = this.usersDao.update(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 更新用户的扩展信息 */
			AUsersExtend usersExtend = users.getUsersExtend() ; 
			if(usersExtend != null)
			{
				this.updateOneUsersExtendService(usersExtend);
			}
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneUsersService(AUsers users, MultipartFile multipartFile) throws Exception
	{
		String uploadFile = ConstatFinalUtil.CONFIG_JSON.getString("website.uploadFile");
		/* 存储的是网址的绝对路径 */
		String souPath = users.getPhotoPath() ;
		
		String truePath = ConstatFinalUtil.CONFIG_JSON.getString("website.truePath");
		String fileName = multipartFile.getOriginalFilename() ;
		/* 网站的相对路径 */
		String tarRelaPath = uploadFile + "/users/" + this.dateFormatUtil.dateStr(new Date()) + "/" + UUID.randomUUID().toString() + 
				fileName.substring(fileName.lastIndexOf("."), fileName.length());
		File tarTrueFile = new File(truePath + tarRelaPath);
		
		if(!tarTrueFile.getParentFile().exists())
		{
			tarTrueFile.getParentFile().mkdirs();
		}
		users.setPhotoPath(tarRelaPath);
		InputStream is = multipartFile.getInputStream() ;
		FileOutputStream fos = new FileOutputStream(tarTrueFile);
		boolean flag = this.fileUtil.copyFile(is, fos);
		if(flag)
		{
			if(souPath != null && !"".equalsIgnoreCase(souPath))
			{
				/* 相对路径 */
				String relaPath = souPath.substring(souPath.indexOf(uploadFile) + uploadFile.length() , souPath.length());
				File souFile = new File(truePath + relaPath);
				if(!souFile.exists())
				{
					ConstatFinalUtil.SYS_LOGGER.error("删除原始文件失败:原始文件路径:{}",souFile.getAbsolutePath());
				}
			}
		}
		
		/* 先更新用户的信息 */
		JSONObject dbJSON = this.updateOneUsersService(users);
		return dbJSON;
	}

	@Override
	public JSONObject deleteOneUsersService(AUsers users)
	{
		/*JSONObject resultJSON = new JSONObject();
		int res = this.usersDao.delete(users);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "删除成功;影响条数:" + res);
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;*/
		return null ;
	}

	@Override
	public AUsers findOneUsersService(Map<String, Object> condMap)
	{
		AUsers users = this.usersDao.findOne(condMap);
		if("true".equalsIgnoreCase(condMap.get("extend") + ""))
		{
			/* 查询关联的地区 */
			Map<String, Object> extMap = new HashMap<String,Object>();
			
			extMap.clear();
			extMap.put("id", users.getRegionId());
			ARegion region = this.systemService.findOneRegionService(extMap);
			users.setRegion(region);
		}
		return users; 
	}

	@Override
	public Map<String, Object> findCondListUsersService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String,Object>() ;
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}
		
		/* 设置分页相关信息 */
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AUsers> list = this.usersDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("list", list);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			resultMap.put("pageInfoUtil", pageInfoUtil);
			return resultMap ;
		}
		List<AUsers> list = this.usersDao.findList(condMap);
		resultMap.put("list", list);
		return resultMap ;
	}
	
	@Override
	public JSONObject saveOneUsersExtendService(AUsersExtend usersExtend)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.usersExtendDao.save(usersExtend);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject updateOneUsersExtendService(AUsersExtend usersExtend)
	{
		JSONObject resultJSON = new JSONObject();

		int res = this.usersExtendDao.update(usersExtend);
		if (res > 0)
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		} else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneUsersExtendService(AUsersExtend usersExtend)
	{
		return null; 
	}

	@Override
	public AUsersExtend findOneUsersExtendService(Map<String, Object> condMap)
	{
		AUsersExtend usersExtend = this.usersExtendDao.findOne(condMap);
		return usersExtend; 
	}

	@Override
	public Map<String, Object> findCondListUsersExtendService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		Map<String, Object> resultMap = new HashMap<String,Object>() ;
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}
		
		/* 设置分页相关信息 */
		if(pageInfoUtil != null)
		{
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			List<AUsersExtend> list = this.usersExtendDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			resultMap.put("list", list);
			resultMap.put("totalRecord", pageInfoUtil.getTotalRecord());
			resultMap.put("pageInfoUtil", pageInfoUtil);
			return resultMap ;
		}
		List<AUsers> list = this.usersDao.findList(condMap);
		resultMap.put("list", list);
		return resultMap ;
	}
}
